#if DEBUG_VERSION
if (!ark) {
  throw new Error("ARK namespace not found!");
}
#endif


/**
 * Class that calls a specified function after its own callback function has
 * been called a set number of times
 */
ark.AggregateCallback = function(onfinished, num) {
  this.current_ = 0;
  this.total_ = num || 0;
  this.onfinished_ = [];
  if (onfinished) {
    this.onfinished_.push(onfinished);
  } 
};

ark.AggregateCallback.prototype.checkIfFinished_ = function() {
  if (this.current_ >= this.total_) {
    while (this.onfinished_.length > 0) {
      var onfinished = this.onfinished_.shift();
      onfinished();
    }
  }
};

ark.AggregateCallback.prototype.addOnFinishedListener = function(onfinished) {
  this.onfinished_.push(onfinished);
  this.checkIfFinished_();
};

ark.AggregateCallback.prototype.getCallback = function() {
  var me = this;
  this.total_++;

  LOG("[AggregateCallback.getCallback]", this.current_, "/", this.total_);
  return function() {
    me.callback();
  };
};

ark.AggregateCallback.prototype.callback = function() {
  this.current_++;
  LOG("[AggregateCallback.callback]", this.current_, " / ", this.total_);
  this.checkIfFinished_();
};
